package com.bilibili.org.controller;

import com.bilibili.basic.util.JsonResult;
import com.bilibili.basic.util.PageList;
import com.bilibili.org.domain.Department;
import com.bilibili.org.query.DepartmentQuery;
import com.bilibili.org.service.IDepartmentService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @GetMapping("/deptTree")
    public List<Department>deptTree(){
        return departmentService.deptTree();
    }
    /**
     * 根据动词查询所有
     * http://localhost:8080/department
     * @return
     */
    @GetMapping
    public List<Department> loadAll() {
        return departmentService.loadAll();
    }

    @GetMapping("/{id}")
    public Department findByid(@PathVariable Long id) {
        return departmentService.loadById(id);
    }

    /**
     * 删除操作
     */
    @DeleteMapping("/{id}")
    public JsonResult remove(@PathVariable("id") Long id) {
        try {
            departmentService.remove(id);
            return JsonResult.men();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.men().setMsg("删除失败");
        }


    }
    /**
     * 添加和修改操作
     */
    @PutMapping
    public JsonResult updateOrAdd(@RequestBody Department department){
        try {
            // 添加操作
            if (department.getId()==null){
                departmentService.save(department);
            // 修改操作
            }else {
                departmentService.update(department);
            }
            return JsonResult.men();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.men().setMsg("操作失败");
        }
    }
    /**
     * 分页操作
     */
    @PostMapping
    public PageList<Department> pageQuery(@RequestBody DepartmentQuery query){
        try {
            return departmentService.pageQuery(query);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageList<>();
        }
    }
    @PatchMapping
    @ApiOperation(value = "批量删除接口")
    public JsonResult patchDel(@RequestBody List<Long> ids){
        try {
            departmentService.patchDel(ids);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return  JsonResult.men().setMsg("删除失败");
        }
    }

}
